import { getOrderInfo, getOrderAddress, buyOrder, subOrder, wxPayInfo, wxPayStatus } from '../../../api/orderpay'
import { formatTime } from '../../../utils/formatTime'
import Schema from 'async-validator'
const app = getApp()
Page({
  data: {
    buyName: '', // 订购人姓名
    buyPhone: '', // 订购人手机号
    blessing: '', // 祝福语
    deliveryDate: '', // 期望送达日期
    show: false, // 期望送达日期弹框
    minDate: new Date().getTime(),
    goodsList: [],
    addressList: []
  },
  // 选择期望送达日期
  onShowDateTimerPopUp() {
    this.setData({
      show: true
    })
  },

  // 期望送达日期确定按钮
  onConfirmTimerPicker(event) {
    const timeRes = formatTime(new Date(event.detail))
    this.setData({
      show: false,
      deliveryDate: timeRes
    })
  },

  // 期望送达日期取消按钮 以及 关闭弹框时触发
  onCancelTimePicker() {
    this.setData({
      show: false,
      minDate: new Date().getTime(),
      currentDate: new Date().getTime()
    })
  },
  // 跳转到收货地址
  toAddress() {
    wx.navigateTo({
      url: '/modules/settingModule/pages/address/list/index'
    })
  },
  async getPageData(){
    const addressId = app.globalData.address.id
    if(addressId){
      this.setData({
        addressList: app.globalData.address
      })
      return
    }
    const { data:addressList } = await getOrderAddress()
    const { goodsId, blessing } = this.data
    const { data: goodsList } = goodsId
      ? await buyOrder({ goodsId, blessing })
      : await getOrderInfo()
    const orderGoods = goodsList.cartVoList.find(item => item.blessing !== '')
    this.setData({
      addressList,
      goodsList,
      blessing: orderGoods? orderGoods.blessing : ''
    })
  },
  validatorPerson(params){
    // 定义验证规则
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    const phoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$'
    const rules = {
      userAddressId: {
        required: true, message: '请选择收货地址'
      },
      buyName: [
        { required: true, message: '请输入订购人姓名' },
        { pattern: nameRegExp, message: '订购人姓名不合法' }
      ],
      buyPhone: [
        { required: true, message: '请输入订购人手机号' },
        { pattern: phoneReg, message: '订购人手机号不合法' }
      ],
      deliveryDate: [
        { required: true, message: '请选择送达日期' }
      ]
    }
    // 实例化
    const validator = new Schema(rules)
    // 验证
    return new Promise( resolve => {
      validator.validate(params, (errors) => {
        if(errors){
          wx.toast({title: errors[0].message})
          resolve({ valid: false })
        }
        else{
          resolve({ valid: true })
        }
      })
    })
  },
  async submitOrder(){
    const { buyName, buyPhone, goodsList: { cartVoList }, deliveryDate, blessing, addressList } = this.data
    const params = {
      buyName,
      buyPhone,
      cartList: cartVoList,
      deliveryDate,
      remarks: blessing,
      userAddressId: addressList.id
    }
    const { valid } = await this.validatorPerson(params)
    if(!valid) return
    const { code, data } = await subOrder(params)
    if(code === 200){
      this.orderNo = data
      try{
        const payParams = await wxPayInfo(this.orderNo)
        console.log(payParams)
        if(payParams.code === 200){
          const payInfo = await wx.requestPayment(payParams.data)
          if(payInfo.errMsg === 'requestPayment:ok'){
            const payStatus = await wxPayStatus(this.orderNo)
            if(payStatus.code === 200){
              wx.redirectTo({
                url: '/modules/orderPayModule/pages/order/list/list',
                success:()=>{
                  wx.toast({title:'支付成功',icon:'success'})
                }
              })
            }
          }
        }
      }
      catch(err){
        wx.toast({title: '支付失败',icon:'error'})
      }
    }
  },
  onShow(){
    this.getPageData()
  },
  onLoad(options){
    this.setData({
      ...options
    })
  },
  onUnload(){
    app.globalData.address = []
  }
  
})
